import { defineStore } from 'pinia'
import { statisticsApi } from '@/axios/request'
import { ElMessage } from 'element-plus'
import { ref, computed } from 'vue'
import axios from 'axios'

// API基础URL
const BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000'
const API_PREFIX = '/api/statistics'

export interface StatisticsResponse {
  labels: string[]
  datasets: Array<{
    label: string
    data: number[]
    backgroundColor?: string | string[]
    borderColor?: string | string[]
    borderWidth?: number
    type?: string
    yAxisID?: string
  }>
  summary?: Record<string, any>
}

export interface AnomalyResponse {
  count: number
  anomalies: Array<{
    record_id: number
    employee_id: string
    employee_name: string
    date: string
    anomaly_types: string[]
    actual_values: {
      day_hours: number
      night_hours: number
      overtime_hours: number
    }
    average_values: {
      day_hours: number
      night_hours: number
      overtime_hours: number
    }
  }>
  summary?: {
    anomaly_types: Record<string, number>
    threshold: number
    period: string
  }
}

// 多维度工时统计响应接口
export interface MultidimensionalWorkhoursResponse {
  data: Array<{
    [key: string]: any
    day_total_hours: number
    night_hours: number
    overtime_hours: number
    record_count: number
    day_hours_percentage: number
    night_hours_percentage: number
    overtime_hours_percentage: number
  }>
  dimensions: string[]
  summary: {
    total_day_hours: number
    total_night_hours: number
    total_overtime_hours: number
    total_records: number
    period: string
  }
}

export const useStatisticsStore = defineStore('statistics', () => {
  // 多维度工时统计
  const multidimensionalWorkhours = ref<MultidimensionalWorkhoursResponse | null>(null)
  const loadingMultidimensionalWorkhours = ref(false)
  
  // 获取多维度工时统计数据
  const getMultidimensionalWorkhours = async (
    dimensions: string[],
    startDate?: string, 
    endDate?: string
  ) => {
    loadingMultidimensionalWorkhours.value = true
    try {
      // 构建查询参数
      const params: Record<string, string> = {
        dimensions: dimensions.join(',')
      }
      if (startDate) params.start_date = startDate
      if (endDate) params.end_date = endDate
      
      console.log('请求多维度工时统计数据，参数:', params)
      // 使用axios直接调用API
      const response = await axios.get(`${BASE_URL}${API_PREFIX}/multidimensional-workhours`, { params })
      console.log('多维度工时统计数据响应:', response.data)
      multidimensionalWorkhours.value = response.data
      return response.data
    } catch (error: any) {
      ElMessage.error(`获取多维度工时统计数据失败: ${error.message}`)
      console.error('获取多维度工时统计数据失败:', error)
      return null
    } finally {
      loadingMultidimensionalWorkhours.value = false
    }
  }
  
  return {
    // 状态
    multidimensionalWorkhours,
    
    // 加载状态
    loadingMultidimensionalWorkhours,
    
    // 方法
    getMultidimensionalWorkhours
  }
}) 